package com.dd.shop4j.website.member.service;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dd.shop4j.common.utils.HttpRequestUtils;
import com.dd.shop4j.member.mapper.MemberInfoMapper;
import com.dd.shop4j.member.mapper.MemberLogMapper;
import com.dd.shop4j.member.model.MemberInfo;
import com.dd.shop4j.member.model.MemberLog;

/**
 * 会员Service
 * @ClassName: MemberService
 * @Description: TODO
 * <ul style="list-style: decimal;">
 *   <li>根据用户名得到会员信息</li>
 *   <li>修改会员信息</li>
 *   <li>记录会员操作日志</li>
 * </ul>
 * @author 唐小恕
 * @date 2013年12月18日 下午10:57:45
 *
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class MemberService {
	
	@Resource MemberInfoMapper memberInfoMapper;
	@Resource MemberLogMapper memberLogMapper;

	/**
	 * 根据用户名得到会员信息
	 * @param username  用户名
	 * @return 会员信息
	 */
	public MemberInfo getMemberInfoByUsername(String username) {
		MemberInfo entity = new MemberInfo();
		entity.setUsername(username);
		List<MemberInfo> data = memberInfoMapper.queryBySelective(entity);
		if (CollectionUtils.isNotEmpty(data)) {
			return data.get(0);
		}
		return null;
	}

	/**
	 * 修改会员信息
	 * @param member 会员信息
	 * @return 成功true,失败false
	 */
	public boolean updateMemberInfo(MemberInfo member) {
		return memberInfoMapper.updateSelectiveByPrimaryKey(member) > 0;
	}
	
	/**
	 * 记录会员操作日志
	 * @param description 日志描述
	 * @param request  请求对象
	 * @return
	 */
	public boolean logger(String description) {
		HttpServletRequest request = HttpRequestUtils.getRequest();
		MemberLog log = new MemberLog();
		log.setRequestDate(new Date());
		log.setRequestIp(request.getRemoteHost());
		String requestUrl = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort() + request.getRequestURI();
		if (StringUtils.isNotEmpty(request.getQueryString())) {
			requestUrl += "?" + request.getQueryString();
		}
		log.setRequestUrl(requestUrl);
		log.setDescription(description);
		return memberLogMapper.insertSelective(log) > 0;
	}
}
